import fs from 'fs';
import path from 'path';

export class BaseModel {
  constructor(filePath, defaultData = []) {
    this.filePath = filePath;
    this.defaultData = defaultData;
  }

  findAll() {
    try {
      if (fs.existsSync(this.filePath)) {
        const fileContent = fs.readFileSync(this.filePath, 'utf8');
        const data = JSON.parse(fileContent);

        // 确保返回的是数组
        if (!Array.isArray(data)) {
          console.warn(`数据文件 ${this.filePath} 格式不正确，不是数组，使用默认数据`);
          this.saveData(this.defaultData);
          return this.defaultData;
        }

        return data;
      } else {
        // 文件不存在，创建默认数据文件
        console.log(`数据文件 ${this.filePath} 不存在，创建默认数据文件`);
        this.saveData(this.defaultData);
        return this.defaultData;
      }
    } catch (error) {
      console.error(`Error reading data from ${this.filePath}:`, error);
      console.error('使用默认数据并尝试修复文件');
      // 尝试修复：保存默认数据
      try {
        this.saveData(this.defaultData);
      } catch (saveError) {
        console.error('修复数据文件失败:', saveError);
      }
      return this.defaultData;
    }
  }

  findById(id) {
    const data = this.findAll();
    return data.find(item => item.id === parseInt(id));
  }

  findOne(query) {
    const data = this.findAll();
    return data.find(item => {
      return Object.keys(query).every(key => item[key] === query[key]);
    });
  }

  create(newItem) {
    const data = this.findAll();
    const newId = data.length > 0 ? Math.max(...data.map(item => item.id)) + 1 : 1;

    const itemWithId = {
      id: newId,
      ...newItem,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    data.push(itemWithId);
    this.saveData(data);
    return itemWithId;
  }

  saveData(data) {
    try {
      const dir = path.dirname(this.filePath);
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
      }
      fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2));
      return true;
    } catch (error) {
      console.error(`Error saving data to ${this.filePath}:`, error);
      return false;
    }
  }

  update(id, updateData) {
    try {
      const data = this.findAll();
      const index = data.findIndex(item => item.id === parseInt(id));

      if (index === -1) {
        return null;
      }

      // 过滤掉 undefined 值，只更新提供的有效字段（允许 null，因为某些字段可能有意识地设置为 null）
      const cleanUpdateData = {};
      Object.keys(updateData).forEach(key => {
        if (updateData[key] !== undefined) {
          cleanUpdateData[key] = updateData[key];
        }
      });

      const updatedItem = {
        ...data[index],
        ...cleanUpdateData,
        updatedAt: new Date().toISOString()
      };

      data[index] = updatedItem;
      this.saveData(data);
      return updatedItem;
    } catch (error) {
      console.error(`Error updating item with id ${id}:`, error);
      return null;
    }
  }

  delete(id) {
    try {
      const data = this.findAll();
      const filteredData = data.filter(item => item.id !== parseInt(id));

      if (filteredData.length === data.length) {
        return false; // Item not found
      }

      this.saveData(filteredData);
      return true;
    } catch (error) {
      console.error(`Error deleting item with id ${id}:`, error);
      return false;
    }
  }
}